/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.msstudio.message;

import com.msstudio.websocket.client.WebSocketClient;
import net.jarlehansen.protobuf.javame.ByteString;

/**
 *
 * @author sunnyz
 */
public class MessageSender {
    WebSocketClient mClient = null;
    public MessageSender(WebSocketClient client)
    {
        mClient = client;
    }
    
    public boolean sendLoginMessage(String username, String password)
    {
        Login login = Login.newBuilder().setUsername(username).setPassword(password).build();
        byte[] loginBytes = null;
        Msg msg = null;
        try {
            loginBytes = login.toByteArray();
            msg = Msg.newBuilder().setMsgHead("Login").    // MsgHead必须为"Login",服务器端根据该字符串构造相应的handler name- "LoginHandler"
                setMsgBody(ByteString.copyFrom(loginBytes, 0, loginBytes.length)).
                build();    
            sendAMessage(msg);            
        } catch (Exception ex)
        {
            return false;
        } 
        finally {  // 必须要有finally, 同时要释放所用的内存
            login = null;
            loginBytes = null;
        }
        return true;
    }
    
    private boolean sendAMessage(Msg msg)
    {
        if (mClient == null) {
            return false;
        }
        try {
            mClient.send(msg.toByteArray());
        } catch (Exception ex)
        {
            return false; //断线
        }
        finally {
            msg = null;
        }
        return true;
    }
}
